package com.gadgets.framework.controller;

import com.gadgets.framework.common.dto.CacheRefreshRequestDTO;
import com.gadgets.framework.common.dto.HttpBaseResp;
import com.gadgets.framework.common.exception.GadgetsServiceException;
import com.gadgets.framework.common.util.StringUtils;
import com.gadgets.framework.start.AbsCacheInitLoaderProcess;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author UncleXiu
 * @version V1.0.0
 * @data 2022-02-10
 */
@RestController
@RequestMapping(method = {org.springframework.web.bind.annotation.RequestMethod.POST,org.springframework.web.bind.annotation.RequestMethod.GET},value = "/cache")
public class CacheRefreshController {

    private final List<AbsCacheInitLoaderProcess> processList = new ArrayList<>();

    /**
     * 缓存刷新
     * @param request                       网络请求
     * @param response                      网络应答
     * @param refreshRequestDTO             缓存刷新信息
     * @throws GadgetsServiceException      服务异常
     * @return                              执行结果
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(method = {org.springframework.web.bind.annotation.RequestMethod.POST,org.springframework.web.bind.annotation.RequestMethod.GET},value = "/refresh.do")
    public HttpBaseResp cacehRefresh(HttpServletRequest request, HttpServletResponse response, CacheRefreshRequestDTO refreshRequestDTO) throws GadgetsServiceException{
        String refreshType = refreshRequestDTO.getCacheType();
        // 由于未知原因，前端未传输刷新类型，则默认为全量刷新
        if(StringUtils.isBlank(refreshType)){
            refreshType = "0";
        }
        for (AbsCacheInitLoaderProcess absCacheInitLoaderProcess : processList) {
            // 遍历执行缓存刷新器
            if(absCacheInitLoaderProcess.judgeRefresh(refreshType)){
                // 如果需要执行，则执行缓存刷新
                absCacheInitLoaderProcess.initLoad();
            }
        }
        return new HttpBaseResp();
    }

    /**
     * 缓存加载器注册
     * @param process   加载器对象
     */
    void addProcessList(AbsCacheInitLoaderProcess process){
        processList.add(process);
    }

}
